package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.domain.Menu;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IMenuService;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
public class LoginController {
    @Autowired
    private IMenuService menuService;

    @Autowired
    private IEmployeeService employeeService ;

    @Autowired
    private IPermissionService permissionService ;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username , String password){
        Employee employee = employeeService.login(username,password);
        if (employee != null){
            HttpSession session = UserContext.getSession();
            UserContext.setEmployee(employee);
            if (!employee.isAdmin()){
                List<String> expressions = permissionService.selectAllExpression(employee.getId());
                UserContext.setExpressions(expressions);
            }

            List<Menu> menus = menuService.selectByTreeDate();
            session = UserContext.getSession();
            session.setAttribute("MENUS",menus);

            boolean admin = employeeService.isAdmin();
            session.setAttribute("admin",admin);


            return new JsonResult(true,"登录成功");
        }else{
            return new JsonResult(false,"登陆失败");
        }
    }


    @RequestMapping("/logout")
    public String logout(){
        HttpSession session = UserContext.getSession();
        session.invalidate();
        return "redirect:/static/login.html" ;
    }

    @RequestMapping("/nopermission")
    public String nopermission(){
        return "common/nopermission" ;
    }


}
